<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Lang;
use app\common\model\Mineral as MineralModel;
use app\common\model\User;
use app\common\model\Tokenlog;
use app\common\model\MineralLog;
use app\common\model\Takeico;
use think\Validate;
use think\Hook;

/**
 * Ajax异步请求接口
 * @internal
 */
class Mineral extends Frontend
{

    protected $noNeedLogin = ['lang'];
    protected $noNeedRight = ['*'];
    protected $layout = 'layout';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
         Hook::add('check_paypwd', function ($paypwd) use ($auth) {
            if ($auth->getUser()['payplaintext'] != $paypwd) {
                $this->error('安全密码不正确');
            }
        });
    }

    /**
     * 我的矿机
     * @return [type] [description]
     */
    public function mymineral()
    {
        $token = $this->auth->getUserToken();
        $this->view->assign('token', $token);
        $mineral = new MineralModel();
        $price = config('site.mineral_price');
        $num = $mineral->where('user_id',$this->auth->id)->where('status','running')->sum('num');
        $total = $mineral->where('user_id',$this->auth->id)->sum('num');
        $today = $mineral->where('user_id',$this->auth->id)->sum('today');
        // $this->view->assign('num', $num);
        // $this->view->assign('num', $num);

        if ($this->request->isAjax()) {

            $page = $this->request->request('page',1);
            $status = $this->request->request('status','running');

            if (!in_array($status, ['running','scrapped'])) {
                $this->error('输入的矿机状态不正确！code running || scrapped');
            }

            $offset = input('offset');
            $limit = input('limit');

            $total=$mineral->where('user_id',$this->auth->id)->where('status',$status)->count();
            $minerals=$mineral
                ->where('user_id',$this->auth->id)
                ->where('status',$status)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $minerals);

            return json($result);
        }
        return $this->view->fetch('',['num'=>$num,'total'=>$total,'today'=>$today,'price'=>$price]);
    }
    /**
     * 购买矿机
     *
     * @param int $num 购买的矿机数量
     * @param [type] $[name] [<description>]
     */
    public function buy_advertisement()
    {
        $num = $this->request->request('num',0);
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);
        if ($num == 0) {
            $this->error('请填写数量');
        }

        $user = $this->auth->getUser();
        $price = config('site.mineral_price');
        $yield = config('site.mineral_yield');
        $expiretime = config('site.mineral_expiretime');
        $token = $this->auth->getUserToken();
        $total = $price*$num;
        if ($token->USD < $total) {
            $this->error('您的USD不足');
        }

        MineralModel::create([
            'user_id'   =>  $this->auth->id,
            'num'       =>  $num,
            'price'     =>  $price,
            'createtime'=>  strtotime(date('Y-m-d')) + 86400,
            'expiretime'=>  strtotime(date('Y-m-d')) + 86400 + ($expiretime*86400),
            'yield'     =>  $yield*$num,
        ]);
        User::tokenlog('USD',$this->auth->id,0,-$total,'buymineral','购买矿机');
        Hook::listen("user_buy_mineral",$user,$total);
        $this->success('购买成功');
    }
       /**
     * 广告包YUSD
     *
     * @param int $num 广告包的数量
     */
    public function transport()
    {
        $num = $this->request->request('num/d',0);
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);

        $transport_min = config('site.mineral_transport_min');
        $transport_multiple = config('site.mineral_transport_multiple');
        $mineral_transport_limit = config('site.mineral_transport_limit');
        $level = $this->auth->getUserinfo()['level'];
        if ($level==0) {
             $this->error('未能划转');
        }
        $tokenlog = new Tokenlog();
        $sum = $tokenlog->where('createtime','> time',date('Y-m-d'))->where('user_id',$this->auth->id)->where('symbol','USD')->where('type','transporttoyb')->sum('num');
        if ($mineral_transport_limit[''.$level] < $sum || $mineral_transport_limit[''.$level] < $sum + $num) {
            $this->error('每日运输超过当前等级运输限制');
        }
        if ($transport_min > $num) {
            $this->error(__('不能少于'.$transport_min));
        }
        if ($num % $transport_multiple != 0) {
            $this->error(__('请输入'.$transport_multiple.'的倍数'));
        }
        $token = $this->auth->getUserToken();
        if ($token->YUSD >= $num) {
            User::tokenlog('YUSD',$this->auth->id,0,-$num,'transport','运输到USD');
            User::tokenlog('USD',$this->auth->id,0,$num,'transportformyusd','运输到USD');
            $this->success('运输成功');
        }else{
            $this->error('数量不足');
        }
    }
     /**
     * 广告云划转DUSD
     *
     * @param int $num 广告云的数量
     */
    public function transportd()
    {
        $num = $this->request->request('num/d',0);
        $paypwd = $this->request->request('paypwd','');
        Hook::listen("check_paypwd",$paypwd);

        $transport_min = config('site.mineral_transport_min');
        $transport_multiple = config('site.mineral_transport_multiple');
        $mineral_transport_limit = config('site.mineral_transport_limit');
        $level = $this->auth->getUserinfo()['level'];
         if ($level==0) {
             $this->error('未能划转');
        }
        $tokenlog = new Tokenlog();
        $sum = $tokenlog->where('createtime','> time',date('Y-m-d'))->where('user_id',$this->auth->id)->where('symbol','USD')->where('type','transporttousd')->sum('num');
        if ($mineral_transport_limit[$level] < $sum || $mineral_transport_limit[$level] < $sum + $num) {
            $this->error('每日运输超过当前等级运输限制');
        }
        if ($transport_min > $num) {
            $this->error(__('不能少于'.$transport_min));
        }
        if ($num % $transport_multiple != 0) {
            $this->error(__('请输入'.$transport_multiple.'的倍数'));
        }
        $token = $this->auth->getUserToken();
        if ($token->DUSD >= $num) {
            User::tokenlog('DUSD',$this->auth->id,0,-$num,'transport','运输到USD');
            User::tokenlog('USD',$this->auth->id,0,$num,'transportformdusd','运输到USD');
            $this->success('运输成功');
        }else{
            $this->error('数量不足');
        }
    }
    // 钱包地址
    public function tokenqrcode(){
      $token = $this->auth->getUserToken();
       return $this->view->fetch('',['token'=>$token]); 
    }

    public function getTransferLogs()
    {
         $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
         $link=parse_url($url, PHP_URL_PATH);
         $arr=explode('.', $link);
         $arrusd=explode('/', $arr[0]); 
        $type = $arrusd[5];
        $tokenlog = new Tokenlog();
        $list = $tokenlog->where('user_id',$this->auth->id)->where('symbol',$type)->order('id desc')->paginate(10);
        return $this->view->fetch('wallet_in_two',['list'=>$list,'type'=>$type]); 
    }
    //提币
    public function wallet_withdraw_money(){
        $mineral_takefto_poundage = config('site.mineral_takefto_poundage');
        $this->view->assign('mineral_takefto', $mineral_takefto_poundage);
         $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
         $link=parse_url($url, PHP_URL_PATH);
         $arr=explode('.', $link);
         $arrusd=explode('/', $arr[0]);  
       

        if ($this->request->isPost()) {
            $num = $this->request->post('num/d',1);
            $tokenaddress = $this->request->post('tokenaddress','');
            $paypwd = $this->request->post('paypwd','');
            Hook::listen("check_paypwd",$paypwd);
            if ($tokenaddress=='') {
                $this->error('请输入钱包地址');
            }
            if ($num=='') {
                $this->error('请输入提币数量');
            }
            $type = $this->request->post('type');
                        $token = $this->request->post('__token__');
            $rule = [
                'num'  => 'require|length:1',
                'tokenaddress'  => 'require|length:1',
                '__token__' => 'token',
            ];

            $msg = [
               
            ];
            $data = [
                'num'  => $num,
                'tokenaddress'  => $tokenaddress,
                '__token__' => $token,
            ];
            $field = [
                'num'   => __('提币数量'),
                'tokenaddress'   => __('提币地址')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if (!in_array($type, ['FAE'])) {
                $this->error();
            }

            $mineral_takefto_min = config('site.mineral_takefto_min');
            $mineral_takefto_poundage = config('site.mineral_takefto_poundage');

            if ($num < $mineral_takefto_min) {
                $this->error('最低提'.$mineral_takefto_min);
            }

            $pre = bcdiv($mineral_takefto_poundage, 100,2);

            $poundage = bcmul($pre,$num,4);

            $token = $this->auth->getUserToken();
            $total = $poundage + $num;
            if ($token->FAE < $total) {
                $this->error('您的FAE不足'.$total);
            }
            if (User::tokenlog('FAE',$this->auth->id,0,-$total,'takeicofto','提币')) {
                Takeico::create([
                    'user_id'   =>  $this->auth->id,
                    'icotype'   =>  'FAE',
                    'tokenaddress'  =>  $tokenaddress,
                    'num'       =>  $num,
                    'reply'     =>  ''
                ]);
                $this->success('提币成功');
            }else{
                $this->error('发生错误');
            }

        }
       return $this->view->fetch('',['type'=>$arrusd[5]]); 
    }
    /**
     * 我的矿场架构 （推荐架构）
     *
     * @param int $referee_id 推荐人的id，传0默认为自己，传其他id为查询团队成员架构
     */
    public function frame()
    {
            if ($_GET['referee_id']!==0) {
                $referee_id=$_GET['referee_id'];
            }else{
                $referee_id=$this->auth->id;
            }
            if ($referee_id == 0) {
                $referee_id = $this->auth->id;
            }
            $user = new User();
            $field = 'id,nickname,username,mobile,level,avatar,status,active';
            $users = $user->where('referee_id',$referee_id)->field($field)->select();
            $shangji = $user->where('id',$referee_id)->value('referee_id');
            if ($shangji<$this->auth->id) {
                $shangji=$this->auth->id;
            }
        return $this->view->fetch('',['list'=>$users,'shangji'=>$shangji]);
    }

    /**
     * 协同挖矿
     *
     * @ApiParams   (name="page", type="int", required=true, description="查询页数")
     */
    public function synergetic()
    {
        $page = $this->request->request('page/d',1);
        $tokenlog = new Tokenlog();
        $token = $this->auth->getUserToken();
        $this->view->assign('token', $token);
        
        $total = $tokenlog->where('user_id',$this->auth->id)->where('type','synergetic')->order('id desc')->sum('num');

        if ($this->request->isAjax()) {
            $offset = input('offset');
            $limit = input('limit');

            $total = $tokenlog
                ->where('user_id',$this->auth->id)
                ->where('type','synergetic')
                ->order('id desc')
                ->count();
            $logs = $tokenlog
                ->where('user_id',$this->auth->id)
                ->where('type','synergetic')
                ->order('id desc')
                ->limit($offset, $limit)
                ->select();
            foreach ($logs as $key => $log) {
                $log->touser;
            }
            $result = array("total" => $total, "rows" => $logs);

            return json($result);
        }

        return $this->view->fetch('',['total'=>$total]);
    }


    /**
     * 获取数字钱包信息
     * @return [type] [description]
     */
    public function wallet()
    {
        $token = $this->auth->getUserToken();
        return $this->view->fetch('',['token'=>$token]);
    }


}
